package com.neusoft.yuejian_01.activity.MJJ;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.neusoft.yuejian_01.R;
import com.neusoft.yuejian_01.base.BaseActivity;
import com.neusoft.yuejian_01.model.Const;
import com.neusoft.yuejian_01.service.TestService;
import com.neusoft.yuejian_01.util.Bimp;
import com.neusoft.yuejian_01.util.FileUtils;
import com.neusoft.yuejian_01.util.ImageItem;
import com.neusoft.yuejian_01.util.PublicWay;
import com.neusoft.yuejian_01.util.Res;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;


public class AddSetPictureActivity extends BaseActivity {
    private GridView noScrollgridview;
    private GridAdapter adapter;
    private View parentView;
    private ArrayList<ImageItem> dataList;
    private PopupWindow pop = null;
    private LinearLayout ll_popup;
    public static Bitmap bimap;
    private int p_id;
    private TextView backset, setPost;
    private EditText postInfo;
    protected Context context;

    @SuppressLint("HandlerLeak")
    public class GridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private int selectedPosition = -1;
        private boolean shape;
        public boolean isShape() {return shape;
        }
        public void setShape(boolean shape) {this.shape = shape;
        }
        public GridAdapter(Context context) {inflater = LayoutInflater.from(context);
        }
        public void update() {
            loading();
        }
        //异步线程随时局部刷新
        /*统计选择的图片数量*/
        public int getCount() {
            if (Bimp.tempSelectBitmap.size() == 9) {
                return 9;
            }
            return (Bimp.tempSelectBitmap.size() + 1);
        }

        public Object getItem(int arg0) {
            return null;
        }

        public long getItemId(int arg0) {
            return 0;
        }

        public void setSelectedPosition(int position) {
            selectedPosition = position;
        }

        public int getSelectedPosition() {
            return selectedPosition;
        }
        //View convertView  item个数，是用来获得指定位置要显示的View
//当要显示一个View就调用一次这个方法。这个方法是ListView性能好坏的关键。
//		方法中有个convertView，这个是Android在为我们而做的缓存机制，展示在界面上的一个item。
//ViewGroup parent 这个属性是加载xml视图时使用
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_published_grida,
                        parent, false);

//				把你getView方法中每次返回的View存起来，可以下次再用。
//				这样做的好处就是不必每次都到布局文件中去拿到你的View，提高了效率
                holder = new ViewHolder();
                holder.image = (ImageView) convertView
                        .findViewById(R.id.item_grida_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
//Bimp.tempSelectBitmapl临时存储照片表
            if (position == Bimp.tempSelectBitmap.size()) {
                holder.image.setImageBitmap(BitmapFactory.decodeResource(
                        getResources(), R.drawable.icon_addpic_unfocused));
                if (position == 9) {
                    holder.image.setVisibility(View.GONE);
                }
            } else {
                //获取图片路径
                holder.image.setImageBitmap(Bimp.tempSelectBitmap.get(position).getBitmap());
            }
            return convertView;
        }

        public class ViewHolder {
            public ImageView image;
        }
       /* 主要用于异步消息的处理*/
        Handler handler = new Handler() {
           public void handleMessage(Message msg) {
                switch (msg.what) {

//					adapter.notifyDataSetChanged();//局部更新，更新可视区域，
//					adapter.notifyDataSetInvalidated();//整体更新，更新所有item对象，如果滑动过，更新后回到初始状态
                    case 1:
                        adapter.notifyDataSetChanged();
                        break;
                }
                super.handleMessage(msg);
            }
        };


// /* 获取图片调用adapter*/
        public void loading() {
            new Thread(new Runnable() {
                public void run() {
                    while (true) {
                        if (Bimp.max == Bimp.tempSelectBitmap.size()) {
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                            break;
                        } else {
                            Bimp.max += 1;
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                        }
                    }
                }
            }).start();
        }
    }

    public String getString(String s) {
        String path = null;
        if (s == null)
            return "";
        for (int i = s.length() - 1; i > 0; i++) {
            s.charAt(i);
        }
        return path;
    }

    protected void onRestart() {
        adapter.update();
        super.onRestart();
    }

    private static final int TAKE_PICTURE = 0x000001;

    public void photo() {

//        使用MediaStore.ACTION_IMAGE_CAPTURE,拍照到指定目录
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
    }
//传送的是照片的目录和地址
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PICTURE:
                if (Bimp.tempSelectBitmap.size() < 9 && resultCode == RESULT_OK) {
//                    获得当前的时间
                    String fileName = String.valueOf(System.currentTimeMillis());
                    Bitmap bm = (Bitmap) data.getExtras().get("data");
                    FileUtils.saveBitmap(bm, fileName);
                    ImageItem takePhoto = new ImageItem();
                    takePhoto.setBitmap(bm);
                    Bimp.tempSelectBitmap.add(takePhoto);
                }
                break;
        }
    }
    //键盘的监听
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //弹出确定退出对话框
            for (int i = 0; i < PublicWay.activityList.size(); i++) {
                if (null != PublicWay.activityList.get(i)) {
                    PublicWay.activityList.get(i).finish();
                }
            }
            System.exit(0);
        }
        return true;
    }



     protected void initView() {
         Res.init(this);

         /**
           * res包含图像数据的资源对象
           * 初始化文件夹路径和R资源
         */
         bimap = BitmapFactory.decodeResource(
                 getResources(),
                 R.drawable.icon_addpic_unfocused);
         //存放所有的list在最后退出时一起关闭
         PublicWay.activityList.add(this);
         //绑定了上传图片的xml
         parentView = getLayoutInflater().inflate(R.layout.activity_selectimg, null);
        setContentView(parentView);
          findViewById(R.id.activity_selectimg_send).setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 uploadImage(dataList);
             }
         });

        setPost = (TextView) findViewById(R.id.activity_selectimg_send);
        postInfo = (EditText) findViewById(R.id.setInfo);
        findViewById(R.id.backm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(RESULT_CANCELED);
                finish();
            }
        });
    }


     protected void initEvents() {
         //自定义弹出窗口
        pop = new PopupWindow(AddSetPictureActivity.this);
        View view = getLayoutInflater().inflate(R.layout.item_popupwindows, null);
//照片选择框
        ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
         //在MainActivity显示窗口
         pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
         //显示布局
        pop.setContentView(view);

        RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
        Button bt1 = (Button) view
                .findViewById(R.id.item_popupwindows_camera);
        Button bt2 = (Button) view
                .findViewById(R.id.item_popupwindows_Photo);
        Button bt3 = (Button) view
                .findViewById(R.id.item_popupwindows_cancel);
        parent.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //点击空白处，取消对话框，就可以结束动画
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                photo();
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(AddSetPictureActivity.this,
                        AlbumActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out);
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });

        noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
        noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        adapter = new GridAdapter(this);
        adapter.update();
        noScrollgridview.setAdapter(adapter);
        noScrollgridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                if (arg2 == Bimp.tempSelectBitmap.size()) {
                    Log.i("ddddddd", "----------");
                    ll_popup.startAnimation(AnimationUtils.loadAnimation(AddSetPictureActivity.this, R.anim.activity_translate_in));
                    pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
                } else {
                    Intent intent = new Intent(AddSetPictureActivity.this,
                            GalleryActivity.class);
                    intent.putExtra("position", "1");
                    intent.putExtra("ID", arg2);
                    startActivity(intent);
                }
            }
        });

    }

    @Override
    protected void initData() {

    }
//传送图片类表
    private void uploadImage(ArrayList<ImageItem> dataList) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Const.BASE_URL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        TestService service = retrofit.create(TestService.class);
        String ppostInfo = postInfo.getText().toString();
        Map<String, RequestBody> maps = new HashMap<>();
        for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
            String newPath = Bimp.tempSelectBitmap.get(i).getImagePath();
            File file = new File(newPath);
            String name = "file" + i + "\"; filename=\"test.jpg";
            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            maps.put(name, requestBody);
        }

        Call<String> call = service.uploadFile(getUser_id(), getC_id(), ppostInfo, maps);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(retrofit2.Call<String> call, Response<String> response) {
                Bimp.tempSelectBitmap.clear();
                Bimp.max=0;
                finish();
            }

            @Override
            public void onFailure(retrofit2.Call<String> call, Throwable t) {
                Toast.makeText(AddSetPictureActivity.this, "something went wrong.", Toast.LENGTH_SHORT).show();
                t.printStackTrace();


            }
        });


    }


}
